var usernameKey = 'encUsername';
var passwordKey = 'encPassword';
var rememberMeKey = 'rememberMe';

function setLocalStorage(obj) {
    if (obj.field.remember === 'on') {
        localStorage.setItem(usernameKey, obj.field.username);
        localStorage.setItem(passwordKey, obj.field.password);
        localStorage.setItem(rememberMeKey, obj.field.remember);
    } else {
        localStorage.removeItem(usernameKey);
        localStorage.removeItem(passwordKey);
        localStorage.removeItem(rememberMeKey);
    }
}

$(function(){
    // 入口函数会优先执行
    layui.use(['jquery', 'layer', 'form'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;

        $('.login-wrapper').removeClass('layui-hide');

        function rememberMeRender() {
            var rememberMe = localStorage.getItem(rememberMeKey);
            if (rememberMe === 'on') {
                if (localStorage.getItem(usernameKey) && localStorage.getItem(passwordKey)) {
                    $('input[name=username]').val(localStorage.getItem(usernameKey));
                    $('input[name=password]').val(localStorage.getItem(passwordKey));
                    $('input[name=remember]').prop('checked', true);
                }
            }
            form.render();
        }

        rememberMeRender();

        // 校验两次密码是否一致
        form.verify({
            confirmPass: function (value) {
                if ($('input[name=password]').val() !== value)
                    return '两次密码输入不一致！';
            }
        });

        // 登录表单提交
        form.on('submit(loginSubmit)', function (obj) {
            obj.field.rememberMe = !!obj.field.remember;
            layer.load(2);
            $.post(app + '/sys/user/doLogin', obj.field, function (res) {
                if (200 === res.code) {
                    // 根据 记住我 是否勾选来设置本地存储
                    setLocalStorage(obj);
                    console.log("登录用户信息：" + JSON.stringify(res));
                    layer.msg('登录成功', {icon: 1, time: 1500}, function () {
                        location.replace('./index');
                    });
                } else {
                    layer.closeAll('loading');
                    layer.msg(res.message, {icon: 5, time: 2000});
                    $('img.login-captcha').trigger('click');
                }
            }, 'JSON');
            return false;
        });

        // 注册表单提交
        form.on('submit(regSubmit)', function (obj) {
            layer.load(2);
            $.post('reg', obj.field, function (res) {
                if (200 === res.code) {
                    layer.msg(res.message, {icon: 1, time: 1500}, function () {
                        location.replace('/login');
                    });
                } else {
                    layer.closeAll('loading');
                    layer.msg(res.message, {icon: 5});
                    $('img.login-captcha').trigger('click');
                }
            }, 'JSON');
            return false;
        });

        function captchaRender() {
            var captchaUrl = app + '/assets/captcha';
            $('img.login-captcha').click(function () {
                this.src = captchaUrl + '?t=' + (new Date).getTime();
            }).trigger('click');
        }

        /* 图形验证码 */
        captchaRender();

        // 完善密码表单提交
        form.on('submit(informationPassSubmit)', function (obj) {
            layer.load(2);
            obj.field.avatar = $('#avatar').attr('src');
            console.log(obj.field);
            $.post(app + '/informationPass', obj.field, function (res) {
                if (200 === res.code) {
                    layer.msg(res.message, {icon: 1, time: 1500}, function () {
                        location.replace('/index');
                    });
                } else {
                    layer.closeAll('loading');
                    layer.msg(res.message, {icon: 5});
                }
            }, 'JSON');
            return false;
        });
    });
});

function getCookie(name) {
    let cookieArr = document.cookie.split("; ");
    for(let i = 0; i < cookieArr.length; i++) {
        let cookiePair = cookieArr[i].split("=");
        if(name === cookiePair[0]) {
            return decodeURIComponent(cookiePair[1]);
        }
    }
    return null;
}

function setCookie(name, value, days) {
    let expires = "";
    if (days) {
        let date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "")  + expires + "; path=/";
}

window.onload = function() {
    const loginExpired = getCookie('loginExpired');
    if (loginExpired === 'true') {
        layer.confirm('登录状态已过期，请重新登录', {
            closeBtn: 0,
            btn: ['确定']
        });
        // 清除或更新此Cookie，防止再次显示消息
        setCookie('loginExpired', '', -1); // 删除Cookie
    }
}